/**
 * User: 蕨菜
 * Date: 2019-05-14
 * Time: 19:28
 * Description: 此文件简要说明
 */

const sequelize = require('sequelize');
const { AppUtil } = require('../util');

exports.associationModel = async (...props) => {
    const [ method, instanceA, ...data ] = props;
    if (AppUtil.isEmpty(method)) {
        throw new Error('关联表method不能为空');
    }
    return await instanceA[ method ](...data);
}

exports.addToModel = async (model, params) => {
    return await model.create(params);
}

exports.updateModelById = async (model, params) => {
    const { id, ...data } = params;
    return await model.update(data, { where: { id } });
}

exports.getDataById = async (model, id) => {
    if (AppUtil.isEmpty(id)) {
        throw new Error(`${model}的id不能为空`)
    }
    return await model.findByPk(id);
}
exports.getDataByIdList = async (model, ids) => {
    const query = AppUtil.isEmpty(ids) ? {} : {
        where: {
            id: {
                [ sequelize.Op.in ]: ids
            }
        }
    };
    return await model.findAll(query);
}

const deleteById = async (model, id) => {
    const result = await model.findByPk(id);

    if (AppUtil.isEmpty(result)) {
        throw new Error('查询不到该id')
    }

    return await result.destroy();
}
exports.deleteById = deleteById;
exports.deleteByIdWithAssociationModel = async (method, model) => {
    await model[ method ]([]);
}

exports.getAll = async (model, query,) => {
    return await model.findAll(query);
}
